import * as React from 'react'
import { Avatar as _Avatar, AvatarProps } from 'antd-mobile'
import { fetchHeaders } from '@/apis/Fetch'

const map_images = new Map<string, string>()
const map_resolves = new Map<string, {(src: string): void}[]>()

export const getCacheSrc = (src: string) => {
  return new Promise<string>(function (resolve) {
    if (!src || /^(https?)?:\/\//.test(src)) {
      return resolve(src)
    }
    const url = map_images.get(src)
    if (url) {
      return resolve(src)
    }
    const resolves = map_resolves.get(src)
    if (resolves) {
      resolves.push(resolve)
      return
    }
    map_resolves.set(src, [resolve])
    return fetch(src, {
      credentials: 'include',
      headers: fetchHeaders(),
    })
      .then(res => res.blob())
      .then(URL.createObjectURL)
      .then(url => {
        map_images.set(src, url)
        map_resolves.get(src)?.forEach(r => r(url))
      })
      .catch((e) => {
        map_resolves.get(src)?.forEach(r => r(url))
      })
  })
}

export const Avatar = (props: AvatarProps) => {
  const { src: _src, ...rest } = props
  const [src, setSrc] = React.useState<string>()
  React.useEffect(function () {
    if (_src) {
      getCacheSrc(_src)
      .then(setSrc)
    }
  }, [_src])
  return <_Avatar {...rest} src={src}/>
}
